﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

using PersianProxy.Common.Library;

namespace PersianProxy.Servers.ASP.NET.Handlers
{
    public class GetAsyncHandler : IHttpAsyncHandler
    {
        private HttpContext _context;
        private WebRequest NewRequest;
        
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            _context = context;

            string url = Security.DecodeChars(context.Request.Path.Remove(0,1));
            if (url.IndexOf(":443") > 0)
            {
                NewRequest = WebRequest.Create("https://" + url.Replace(":443",""));
            }
            else
                NewRequest = WebRequest.Create("http://" + url);
    
            NewRequest.Proxy = new WebProxy();
            return NewRequest.BeginGetResponse(cb, extraData);
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            _context.Response.ContentType = Common.GetContentType(_context.Request.CurrentExecutionFilePath);

            string rss = String.Empty;
            WebResponse NewResponse = NewRequest.EndGetResponse(result);
            using (NewResponse)
            {
                Stream reader = NewResponse.GetResponseStream();

                int bytesRead = 0;
                int totalBytesRead = 0;
                byte[] buffer = new byte[50000];
                while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    totalBytesRead += bytesRead;
                    _context.Response.OutputStream.Write(buffer, 0, bytesRead);
                }
            }
            
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            throw new Exception("The ProcessRequest method is not implemented.");
        }
    }
}